package com.itmck.cotroller;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {


    @GetMapping("/login")
    public String login() {
        return "/login";
    }

//    @GetMapping({"","/","/index"})
//    public String index() {
//        return "/index";
//    }

    @GetMapping({"","/","/index"})
    public String index(Model model) {
        /**
         *
         * 1)主要是通过SecurityContextHolder获取到上下文SecurityContext，
         * 2)通过SecurityContext获取到权限信息Authentication，
         * 3)最后通过Authentication获取到当前的登录信息：
         *
         *
         */
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if("anonymousUser".equals(principal)) {
            model.addAttribute("name","anonymous");
        }else {
            User user = (User)principal;
            model.addAttribute("name",user.getUsername());
        }
        return "/index";
    }

}